// testing.ts
// const util = require('../../utils/util.js')

import  {formatTime}  from '../../utils/util'
import { apis } from '../../apis/apis'
import {requestPromise} from '../../utils/requestPromise'
Component({
  data: {
    rewardedVideoAd:<any>null,
    questions: <any>[],//问题列表
    currentQuestionIndex: 0,//当前问题下标
    fullBarWidth: 600,//总进度条长度
    activeBarWidth: 0,//已完成的进度条长度
    currentQuestion: {},//当前问题
    answers: <any>[],//答案
    finish:<boolean>false,//是否已完成的标识
    examId:0,
    answerLock:<boolean>false,
  },
  methods: {
    adLoad() {
      console.log('Banner 广告加载成功')
    },
    adError(err:any) {
      console.error('Banner 广告加载失败', err)
    },
    adClose() {
      console.log('Banner 广告关闭')
    },
    clickSubmit(){
      let _that = this;
      wx.showModal({
        title: '提交答案', //提示的标题
        content: '只需要观看一小段广告之后就可以查看你的答案了', //提示的内容
        success: function(res) {
          if(res.confirm) {
            _that.data.rewardedVideoAd.show().then(() => console.log('激励视频 广告显示'))
          } else if (res.cancel) {
            console.log('用户点击了取消')
          }
        }
      })
    },
    //提交整份答案
    submitAnswer(){
      let _th = this;
      if(_th.data.questions.length - 1 != _th.data.currentQuestionIndex){
        return;
      }
      requestPromise({
        url:apis.submitAnswer,
        method:"POST",
        data:{
          answers:_th.data.answers,
          exam_id:_th.data.examId,
        },
      }).then((res:any)=>{
        const title = res.data.data.title;
        const answerGroup = res.data.data.answerGroup;
        wx.setStorageSync('result',{title:title,answerGroup:answerGroup});
        let history = wx.getStorageSync('history') || [];
        if(history.length == 5){
          history.pop();
        }
        history.unshift({title:title,answerGroup:answerGroup,time:formatTime(new Date)});
        wx.setStorageSync('history',history);
        wx.navigateTo({
          url: '/pages/result/result',
          // success:(res)=>{
          //   // 发送一个事件
          //   res.eventChannel.emit('toResult',{ title: title,answerGroup:answerGroup })
          // }
        })
      })
      // request({
      //   url:apis.submitAnswer,
      //   method:"POST",
      //   data:{
      //     answers:_th.data.answers,
      //     exam_id:_th.data.examId,
      //   },
      //   header: {
      //     'Accept': 'application/json', // 默认值
      //   },
      //   success:function(res:any){
      //     const title = res.data.data.title;
      //     const answerGroup = res.data.data.answerGroup;
      //     wx.setStorageSync('result',{title:title,answerGroup:answerGroup});
      //     let history = wx.getStorageSync('history') || [];
      //     if(history.length == 5){
      //       history.pop();
      //     }
      //     history.unshift({title:title,answerGroup:answerGroup,time:formatTime(new Date)});
      //     wx.setStorageSync('history',history);
      //     wx.navigateTo({
      //       url: '/pages/result/result',
      //       // success:(res)=>{
      //       //   // 发送一个事件
      //       //   res.eventChannel.emit('toResult',{ title: title,answerGroup:answerGroup })
      //       // }
      //     })
      //   },
      // })
    },
    //点击答案
    clickAnswer(event: any) {
      // if (this.data.answerLock == true){
      //   return;
      // }
      let questionId = event.target.dataset.qid;
      let answerId = event.target.dataset.aid;
      let len = this.data.answers.length
      for (let i = 0; i < len; i++) {
        if (this.data.answers[i].questionId == questionId) {
          this.setData({
            ['answers[' + i + '].answerId']: answerId,
          })
        }
      }
      // this.setData({
      //   answerLock:true,
      // })
      this.questionJump({ target: { dataset: { action: 'next' } } })
    },
    //计算进度条
    calculateActiveBarWidth() {
      let _th = this;
      let newActiveBarWidth = (_th.data.currentQuestionIndex + 1) / (_th.data.questions.length) * _th.data.fullBarWidth
      this.setData({
        activeBarWidth: newActiveBarWidth,
      })
    },
    //上一题下一题
    questionJump(event: any) {
      let _th = this;
      let newIndex = 0;
      let action = event.target.dataset.action;
      if (action == 'next') {
        if(_th.data.answers[_th.data.currentQuestionIndex].answerId == 0){
          wx.showToast({
            title:"请先完成这题",
            icon:'error',
          })
          return false;
        }
        newIndex = _th.data.currentQuestionIndex + 1
      }
      if (action == 'prev') {
        newIndex = _th.data.currentQuestionIndex - 1
      }
      if (newIndex < 0) {
        return;
      }
      if (newIndex >= _th.data.questions.length) {
        _th.setData({
          finish: true,
        })
        return;
      }
      setTimeout(function(){
        _th.setData({
          currentQuestionIndex: newIndex
        })
        _th.getCurrentQuestion();
        _th.calculateActiveBarWidth();
        // if(_th.data.answerLock == true){
        //   _th.setData({
        //     answerLock: false,
        //   })
        // }
      }, 200);
      return true;
    },
    //获取当前的问题
    getCurrentQuestion() {
      let _th = this;
      let currentQuestionTmp = _th.data.questions[_th.data.currentQuestionIndex];
      _th.setData({
        currentQuestion: currentQuestionTmp
      })
    },
    //初始化答案
    initAnswers() {
      let defaultAnswer = <any>[];
      this.data.questions.forEach((q: { id: any; }) => {
        let answer = {
          questionId: q.id,
          answerId: 0
        }
        defaultAnswer.push(answer);
      });
      this.setData({
        answers: defaultAnswer
      })
    },
    //通过接口获取问题列表
    getQuestionList(examId:number){
      let _th = this;
      requestPromise({
        url:apis.questionList,
        method:"GET",
        data:{
          exam_id:examId,
        },
      }).then((res:any)=>{
        _th.setData({
          questions:res.data.data
        });
        wx.removeStorageSync('result');
        _th.getCurrentQuestion();
        _th.initAnswers();
      })
    },
    onLoad(option:any) {
      this.setData({
        examId:option.id,
      });
      this.getQuestionList(option.id);
      console.log(223);
      if(wx.createRewardedVideoAd){
        console.log(332);
        this.data.rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-555d04a4e7fa3410' })
        this.data.rewardedVideoAd.onLoad(() => {
          console.log('onLoad event emit')
        })
        this.data.rewardedVideoAd.onError((err:any) => {
          console.log('onError event emit', err)
        })
        this.data.rewardedVideoAd.onClose((res:any) => {
          console.log('onClose event emit', res)
          if (res && res.isEnded) {
            this.submitAnswer()
          } else {
            // 播放中途退出，不下发游戏奖励
            // this.submitAnswer()
          }
        })
      }
    },
  },
  lifetimes: {
    attached() {
    
    },
  },
})
